package com.kczd.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.kczd.client.R;
import com.kczd.util.Common;
import com.kczd.util.NetRET;
import com.kczd.util.SysApplication;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FindBackPasswordActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_phone;
    private EditText et_passwd;
    private EditText et_checkkey;

    private Button iv_getCheckkey;
    private Button iv_sub_register;
    private ImageView iv_back;

    //
    int i = 60;
    boolean bool_subcheckkey = false;
    SweetAlertDialog pDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_back_password);
        initView();
        initMobSMSSDK();
        // 多activity管理
        SysApplication.getInstance().addActivity(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void initView(){
        iv_getCheckkey = (Button) findViewById(R.id.iv_getCheckkey);
        iv_sub_register = (Button) findViewById(R.id.iv_sub_register);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_passwd = (EditText) findViewById(R.id.et_passwd);
        et_checkkey = (EditText) findViewById(R.id.et_checkkey);
        iv_back = (ImageView) findViewById(R.id.iv_back);

        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading");
        pDialog.setCancelable(false);

        iv_getCheckkey.setOnClickListener(this);
        iv_sub_register.setOnClickListener(this);
        iv_back.setOnClickListener(this);
    }

    /**
     * 初始化短信SDK
     */
    private void initMobSMSSDK() {
        SMSSDK.initSDK(this, Common.token1, Common.token2);
        EventHandler eventHandler = new EventHandler() {
            /**
             * 在操作之后被触发
             *
             * @param event
             *            参数1
             * @param result
             *            参数2 SMSSDK.RESULT_COMPLETE表示操作成功，为SMSSDK.
             *            RESULT_ERROR表示操作失败
             * @param data
             *            事件操作的结果
             */
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        // 注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);

    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_sub_register:
                if(bool_subcheckkey){
                    if(et_checkkey.getText().toString().isEmpty()){
                        Toast.makeText(getApplicationContext(), "请输入验证码！",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    pDialog.show();

                    SMSSDK.submitVerificationCode("86", et_phone.getText().toString(),
                            et_checkkey.getText().toString());
                }
                else{
                    if(et_passwd.getText().toString().isEmpty()){
                        Toast.makeText(getApplicationContext(), "请输入您的新密码！",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }else{
                        pDialog.show();

                        new Thread(){
                            @Override
                            public void run()
                            {
                                registerHandle();
                            }
                        }.start();
                    }
                }
                break;

            case R.id.iv_getCheckkey:
                i = 60;
                bool_subcheckkey = true;
                String phoneNums = et_phone.getText().toString();
                // 1. 通过规则判断手机号
                if (!judgePhoneNums(phoneNums)) {
                    return;
                } // 2. 通过sdk发送短信验证
                SMSSDK.getVerificationCode("86", phoneNums);

                // 3. 把按钮变成不可点击，并且显示倒计时（正在获取）
                iv_getCheckkey.setClickable(false);
                iv_getCheckkey.setText("重新发送(" + i-- + ")");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 60; i > 0; i--) {
                            handler.sendEmptyMessage(-9);
                            if (i <= 0) {
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(-8);  // 在30秒后重新显示为获取验证码
                    }
                }).start();

                // 4. 打开广播来接受读取短信
                break;

            case R.id.iv_back:
                this.finish();
                break;

            default:
                break;
        }
    }
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                iv_getCheckkey.setText("重新发送(" + i-- + ")");
            } else if (msg.what == -8) {
                iv_getCheckkey.setText("获取验证码");
                iv_getCheckkey.setClickable(true);
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示新好友
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                        Toast.makeText(getApplicationContext(), "手机验证成功",
                                Toast.LENGTH_SHORT).show();
                        bool_subcheckkey = false;
                        pDialog.dismiss();
                        iv_getCheckkey.setVisibility(View.GONE);
                        et_checkkey.setEnabled(false);
                        iv_sub_register.setText("确认修改");
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), "验证码已发送",
                                Toast.LENGTH_SHORT).show();
                        bool_subcheckkey = true;
                        iv_sub_register.setText("验证手机");
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  this.unregisterReceiver(smsBroadcastReceiver);
        SMSSDK.unregisterAllEventHandler();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.register, menu);
        return true;
    }

    /**
     * 判断手机号码是否合理
     *
     * @param phoneNums
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (isMatchLength(phoneNums, 11) && isMobileNO(phoneNums)) {
            return true;
        }
        Toast.makeText(this, "手机号码输入有误！", Toast.LENGTH_SHORT).show();
        return false;
    }

    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        } else {
            return str.length() == length ? true : false;
        }
    }
    public static boolean isMobileNO(String mobileNums) {
        String telRegex = "[1][3578]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (mobileNums.isEmpty())
            return false;
        else
            return mobileNums.matches(telRegex);
    }

    String url = Common.net_addr + "itf/tx_change_password.php";
    Handler registerhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                pDialog.dismiss();
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
                    startActivity(new Intent(FindBackPasswordActivity.this,LoginActivity.class));
                    finish();
//                    Toast.makeText(getApplicationContext(),
//                            "修改成功！请返回登陆", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(),
                            "修改失败："+jsonResult.getString("err"), Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    public void registerHandle() {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("phone", et_phone.getText().toString())
                .add("new_pswd", et_passwd.getText().toString())
                .add("utype", Common.utype)
                .add("tran_type", Common.tran_type)
                .build();
        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            registerhandler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
